import { ElMessage } from 'element-plus'
import { ref } from 'vue'

interface Option {
  duration?: number
  isDebounce?: boolean,
  message?: string
}

interface State {
  timeId: number | null
  isShowMessage: any
  showTaskMessage: (option?: Option|string) => any,
  ShowMessageCallback?: Function
}

const normalOption = {
  duration: 5000, // 默认5秒
  isDebounce: true,
  message: undefined
}

/**
 * @param {Option} option 展示状态的配置项
 */
const showTaskMessage = (option: Option|string = normalOption) => {
  const stateOption: Option = getOption(option)

  // 防抖判断
  if (state.timeId && stateOption.isDebounce) clearTimeout(state.timeId)

  // 展示状态窗
  state.isShowMessage.value = true

  // 文本提示
  if (stateOption.message) ElMessage.success(stateOption.message)

  // 定时器关闭
  state.timeId = setTimeout(() => {
    state.isShowMessage.value = false
  }, stateOption.duration);
}

const getOption = (option: any) => {
  // 解决直接on在button等元素上，option会接受成event事件对象
  if (option instanceof PointerEvent) return normalOption
  if (typeof option === "string") return {...normalOption, message: option}

  option.duration = option.duration ?? normalOption.duration
  option.isDebounce = option.isDebounce ?? normalOption.isDebounce
  return option
}

const state: State = {
  timeId: null,
  isShowMessage: ref(),
  showTaskMessage,
  ShowMessageCallback: () => {}
}

/**
 * 任务状态栏展示 初始化自定义hooks
 * @param {Boolean} isShowMessage 默认值: false， 控制是否展示新的状态,
 * @param {Function} ShowMessageCallback 展示后的回调
 * @returns {
 *  isShowMessage: ref
 *  ShowMessageCallback: Function
 * }
 */
export const useTaskHooks = (isShowMessage: boolean = false, ShowMessageCallback?: Function) => {
  state.isShowMessage.value = isShowMessage
  state.ShowMessageCallback = ShowMessageCallback
  return state
}

/**
 * 展示任务栏提示的方法
 * @param {Option} option 
 */
export const ShowTaskMessage = (option?: Option|string) => {
  return state.showTaskMessage(option)
}
